package cn.chenxiejia;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @version : V1.0
 * @program: maven
 * @ClassName: Imges8
 * @Description: 条形码的创建
 * @Author: chenxiejia
 * @Date: 2022/1/24 21:45
 */
public class Imges8 {
    public static void main(String[] args) {
        try {
            tiaoxing("6923790798701");
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void tiaoxing(String contents) throws WriterException, IOException {
        //设置编码格式
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        //设置条形码的号码、编码方式、小及大编码格式
        var bm = new MultiFormatWriter().encode(contents, BarcodeFormat.EAN_13, 300, 200, hints);
        //创建画板
        var i = MatrixToImageWriter.toBufferedImage(bm);
        ImageIO.write(i, "png", new File("img/tiaoxing.png"));
        BufferedImage j = new BufferedImage(400, 300, 2);
        var m = j.createGraphics();
        m.setColor(Color.WHITE);
        m.fillRect(0, 0, j.getWidth(), j.getHeight());
        m.drawImage(i, (j.getWidth() - i.getWidth()) / 2, (j.getHeight() - i.getHeight()) / 2, null);
        String text = "6923790798701";
        m.setColor(Color.BLACK);
        Font font = new Font("微软雅黑", Font.BOLD, 33);
        var fm = m.getFontMetrics(font);
        var tw = fm.stringWidth(text);
        font = font.deriveFont(20f);
        m.setFont(font);
        m.drawString(text, 120, j.getHeight() - fm.getDescent() - 10);
        m.dispose();
        ImageIO.write(j, "png", new File("img/2.png"));
    }


}
